package com.graph;

public class Solution1905 {
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int res = 0;
        boolean[][] visited = new boolean[grid2.length][grid2[0].length];
        for (int i = 0; i < grid2.length; i++) {
            for (int j = 0; j < grid2[0].length; j++) {
                if (!visited[i][j] && grid2[i][j] == 1) {
                    if (dfs(grid2, grid1, visited, i, j)) {
                        res++;
                        System.out.println("" + i + j);
                    }
                }
            }
        }
        return res;
    }

    public boolean dfs(int[][] grid2, int[][] grid1, boolean[][] visited, int i, int j) {
        if (i < 0 || i >= grid2.length || j < 0 || j >= grid2[0].length) return true;
        if (visited[i][j] || grid2[i][j] == 0) return true;
        visited[i][j] = true;
        boolean b1 = dfs(grid2, grid1, visited, i - 1, j);
        boolean b2 = dfs(grid2, grid1, visited, i + 1, j);
        boolean b3 = dfs(grid2, grid1, visited, i, j - 1);
        boolean b4 = dfs(grid2, grid1, visited, i, j + 1);
        boolean flag = b1 && b2 && b3 && b4;
        if (grid1[i][j] == 0) return false;
        return flag;
    }
}
